import { useState, useEffect } from 'react';
import { Popup, Picker, } from 'react-vant';
import SvgIcon from '../../components/SvgIcon/index';
import './index.less';
import {
  staticActionList,
  timeColumn3,
  timeColumn2,
  workTime12,
  workTime14,
  workTime560,
  deviceId,
} from '../../utils/staticData';
import { IActionData } from '../../types/IContext';

export default function Action({
  propsAction,
  onLoopClick,
  onActionChange
}: any) {
  const Hejia = (window as any).Hejia;
  const { isOnline, appointment, Workinghours, mode, fault, status } =
    propsAction;
  const [visibleStr, setVisibleStr] = useState<String>('');
  const [timeTitle, setTimeTitle] = useState('工作时长');
  const [appTitle, setAppTitle] = useState('预约');
  const [columns, setColumns] = useState(timeColumn2());
  const [workColumns, setWorkColumns] = useState(workTime12());

  const state = {
    timerVisible: 'workTime',
    appVisible: 'appointment'
  };

  let _staticActionList = staticActionList;

  const [appValue, setAppValue] = useState<string[]>(['1']);
  const [timerValue, setTimerValue] = useState<string[]>(['1']);

  const [disabledList, setDisabledList] = useState<string[]>(['']);
  const getDisabled = (): void => {
    if (
      !isOnline ||
      [1, 2, 3].includes(status) ||
      fault > 0 ||
      (status == 0 && [1, 7, 0].includes(mode))
    ) {
      setDisabledList(['workTime', 'appointment']);
    } else {
      if (status == 0) {
        if (mode == 2 || mode == 3) {
          setDisabledList(['workTime']);
        } else {
          setDisabledList(['']);
        }
      }
    }
  };

  useEffect(() => {
    getDisabled();
  }, [isOnline, mode, fault, status]);

  useEffect(() => {
    if (mode === 4 || mode === 5) {
      setColumns(timeColumn3());
    } else {
      setColumns(timeColumn2());
    }
    // 煮粥
    if (mode === 4) {
      setWorkColumns(workTime12());
    }
    // 煲汤
    if (mode === 5) {
      setWorkColumns(workTime14());
    }
    // 卤煮
    if (mode === 6) {
      setWorkColumns(workTime560());
    }
  }, [mode]);

  // 工作时长
  useEffect(() => {
    setTimerValue([`${Workinghours}`]);
    if (mode === 7) {
      _staticActionList[0].val = '未设置';
    } else if (mode === 2) { // mode=2 快煮饭，8min进入倒计时，大于8min的数据不显示
      _staticActionList[0].val = Workinghours <= 8 && Workinghours > 0 ? `${Workinghours}分钟` : '未设置';
    } else if (mode === 3) { // mode=3 精煮饭，10min进入倒计时，大于10min的数据不显示
      _staticActionList[0].val = Workinghours <= 10 && Workinghours > 0 ? `${Workinghours}分钟` : '未设置';
    } else {
      _staticActionList[0].val = Workinghours ? `${Workinghours}分钟` : '未设置';
    }
  }, [Workinghours]);

  // 预约
  useEffect(() => {
    setAppValue([`${appointment}`]);
    _staticActionList[1].val = appointment ? `${appointment}分钟` : '未设置';
  }, [appointment]);

  const onClose = () => {
    setVisibleStr('');
    setTimeout(() => {
      onLoopClick(true);
    }, 2000);
  };
  const onOpen = () => {
    onLoopClick(false);
  };

  const onAppCancel = () => {
    _staticActionList[1].val = '未设置';
    onActionChange(0, 'appointment');
    onClose();

    Hejia.setControlParam(
      {
        // deviceId,
        parameters: {
          param: [
            {
              name: 'reserve',
              content: 0
            }
          ]
        }
      },
      function () {
        // success, no response
        console.log('success');
      },
      function (msg: string, obj: any) {
        console.log(msg + obj.resultCode + obj.resultCodeMessage);
      }
    );
  };

  const onClickAction = (key: string): void => {
    setVisibleStr(key);
    if (key === 'timer') {
      if (Workinghours) {
        setTimeTitle('编辑工作时长');
      } else {
        setTimeTitle('工作时长');
      }
    } else if (key === 'app') {
      if (appointment) {
        setAppTitle('编辑预约');
      } else {
        setAppTitle('预约');
      }
    }
  };

  const itemEle = _staticActionList.map((item: IActionData) => {
    return (
      <div className="action-item" key={item.id}>
        {disabledList.includes(item.key) && <div className="mask"></div>}
        <div className="content" onClick={() => onClickAction(item.key)}>
          <div className="icon">
            <SvgIcon name={`${item.svg}`} size="34" />
          </div>
          <div className="left">
            <div className="title">{item.title}</div>
            <div className="num">{item.val}</div>
          </div>
        </div>
      </div>
    );
  });

  return (
    <div className="action">
      {itemEle}

      {/* 工作时长 0-120 step=1 */}
      <Popup
        round
        visible={state.timerVisible === visibleStr}
        position="bottom"
        onOpen={onOpen}
        onClose={onClose}
      >
        <div className="time-wrapper">
          <Picker
            value={timerValue}
            title={timeTitle}
            placeholder=""
            confirmButtonText="确定"
            columns={workColumns}
            onCancel={() => setVisibleStr('')}
            onConfirm={(val: any) => {
              _staticActionList[0].val = `${val}分钟`;
              onActionChange(val, 'timer');
              onClose();

              Hejia.setControlParam(
                {
                  // deviceId,
                  parameters: {
                    param: [
                      {
                        name: 'Workinghours',
                        content: val
                      }
                    ]
                  }
                },
                function () {
                  // success, no response
                  console.log('success');
                },
                function (msg: string, obj: any) {
                  console.log(msg + obj.resultCode + obj.resultCodeMessage);
                }
              );
            }}
          />
          <div className="unit">分钟</div>
        </div>
      </Popup>
      {/* 预约弹框 */}
      <Popup
        round
        visible={state.appVisible === visibleStr}
        position="bottom"
        onOpen={onOpen}
        onClose={onClose}
      >
        <div className="time-wrapper">
          <Picker
            value={appValue}
            title={appTitle}
            placeholder=""
            confirmButtonText="确定"
            columns={columns}
            onCancel={() => setVisibleStr('')}
            onConfirm={(val: any) => {
              _staticActionList[1].val = `${val}分钟`;

              onActionChange(val, 'appointment');
              onClose();

              Hejia.setControlParam(
                {
                  // deviceId,
                  parameters: {
                    param: [
                      {
                        name: 'reserve',
                        content: val
                      }
                    ]
                  }
                },
                function () {
                  // success, no response
                  console.log('success');
                },
                function (msg: string, obj: any) {
                  console.log(msg + obj.resultCode + obj.resultCodeMessage);
                }
              );
            }}
          />
          <div className="unit">分钟</div>
        </div>
        {!!appointment && (
          <div className="btn-cancel" onClick={onAppCancel}>
            取消预约
          </div>
        )}
      </Popup>
    </div>
  );
}
